package org.jeecg.modules.jiucxldj.controller;

import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.TypeReference;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.MinioUtil;
import org.jeecg.modules.jiucxldj.vo.JiucxlResource;
import org.jeecg.modules.jiucxldj.vo.JiucxlRs;
import org.jeecg.modules.workflow.utils.ProcessKit;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.jiucxldj.entity.AgJiucxldjResource;
import org.jeecg.modules.jiucxldj.entity.AgJiucxldj;
import org.jeecg.modules.jiucxldj.vo.AgJiucxldjPage;
import org.jeecg.modules.jiucxldj.service.IAgJiucxldjService;
import org.jeecg.modules.jiucxldj.service.IAgJiucxldjResourceService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 纠察巡逻登记
 * @Author: jeecg-boot
 * @Date:   2020-07-14
 * @Version: V1.0
 */
@Api(tags="纠察巡逻登记")
@RestController
@RequestMapping("/jiucxldj/agJiucxldj")
@Slf4j
public class AgJiucxldjController {
	@Autowired
	private IAgJiucxldjService agJiucxldjService;
	@Autowired
	private IAgJiucxldjResourceService agJiucxldjResourceService;

	@PutMapping(value = "/edit4degnj")
	public Result<?> edit4degnj(@RequestBody AgJiucxldjPage agJiucxldjPage) {
		AgJiucxldj agJiucxldj = new AgJiucxldj();

		BeanUtils.copyProperties(agJiucxldjPage, agJiucxldj);
		AgJiucxldj agJiucxldjEntity = agJiucxldjService.getById(agJiucxldj.getId());
		if(agJiucxldjEntity==null) {
			return Result.error("未找到对应数据");
		}
		agJiucxldjService.updateMain(agJiucxldj, agJiucxldjPage.getAgJiucxldjResourceList());

		return Result.ok("编辑成功!");
	}

	List<String> resourceFileList;

	 void unZip(InputStream is) throws Exception {
		 resourceFileList = new ArrayList<>();

		 ZipInputStream zipInputStream = new ZipInputStream(is);
		 ZipEntry zipEntry = null;
		 int BUFFER = 1024 * 1024;
		 byte[] buffer = new byte[BUFFER];//缓冲器
		 int readLength = 0;//每次读出来的长度

		 String dstPath = System.getProperty("java.io.tmpdir");
		 System.out.println(dstPath);

		 while((zipEntry = zipInputStream.getNextEntry()) != null) {
			 if (zipEntry.isDirectory()) {//若是zip条目目录，则需创建这个目录
				 File dir = new File(dstPath + File.separator + zipEntry.getName());
				 if (!dir.exists()) {
					 dir.mkdirs();
				 }

				 continue;
			 }

			 String fullPath = dstPath + File.separator + zipEntry.getName();
			 System.out.println("unzip file name: " + fullPath);
			 File file = new File(fullPath);

			 OutputStream outputStream = new FileOutputStream(file);
			 while ((readLength = zipInputStream.read(buffer, 0, BUFFER)) != -1) {
				 outputStream.write(buffer, 0, readLength);
			 }
			 outputStream.close();

			 resourceFileList.add(file.getAbsolutePath());
		 }
	 }

	 String readToString(String fileName) {
		 String encoding = "UTF-8";
		 File file = new File(fileName);
		 Long filelength = file.length();
		 byte[] filecontent = new byte[filelength.intValue()];
		 try {
			 FileInputStream in = new FileInputStream(file);
			 in.read(filecontent);
			 in.close();
		 } catch (FileNotFoundException e) {
			 e.printStackTrace();
		 } catch (IOException e) {
			 e.printStackTrace();
		 }
		 try {
			 return new String(filecontent, encoding);
		 } catch (UnsupportedEncodingException e) {
			 System.err.println("The OS does not support " + encoding);
			 e.printStackTrace();
			 return null;
		 }
	 }

	 @RequestMapping(value = "/importAndroidData", method = RequestMethod.POST)
	 public Result<?> importAndroidData(HttpServletRequest request, HttpServletResponse response) {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		 for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			 MultipartFile file = entity.getValue();// 获取上传文件对象

			 try {
				 String tmpdir = System.getProperty("java.io.tmpdir");

				 unZip(file.getInputStream());

				 String json = readToString(tmpdir + File.separator + "archiving" + File.separator +  "index.json");

				 List<JiucxlRs> list = JSON.parseObject(json, new TypeReference<List<JiucxlRs>>() {});
				 for (JiucxlRs jiucxlRs: list
					  ) {
					 AgJiucxldj agJiucxldj = new AgJiucxldj();
					 agJiucxldj.setCreateTime(new Date());
					 agJiucxldj.setShijsj(jiucxlRs.getCreateTime());
					 agJiucxldj.setName(jiucxlRs.getName());
					 agJiucxldj.setBeiz(jiucxlRs.getRemark());
					 agJiucxldj.setCardno(jiucxlRs.getCardNo());
					 agJiucxldj.setSysOrgCode(jiucxlRs.getOrgId());
					 agJiucxldj.setJiucfl(jiucxlRs.getType());

					 String today = new SimpleDateFormat("yyyy-MM-dd_").format(new Date());
					 today += String.format("%03d", agJiucxldjService.count());
					 agJiucxldj.setDaorxh(today);

					 List<AgJiucxldjResource> agJiucxldjResourceList = new ArrayList<>();
					 for (JiucxlResource jiucxlResource: jiucxlRs.getResource()
						  ) {
						 AgJiucxldjResource agJiucxldjResource = new AgJiucxldjResource();
						 agJiucxldjResource.setFilename(jiucxlResource.getFileName());
						 // minio 上传
						 String url = findFileAndUpload2Minio(jiucxlResource.getFileName());
						 agJiucxldjResource.setSavepath(url);

						 agJiucxldjResourceList.add(agJiucxldjResource);

					 }

					 agJiucxldjService.saveMain(agJiucxldj, agJiucxldjResourceList);
				 }

			 } catch (Exception error) {
				 System.out.println(error.getMessage());
			 }
		 }

		 return Result.ok("文件导入成功！");
	 }

	 private String findFileAndUpload2Minio(String fileName) {
	 	String filePath = null;

		for(String str: resourceFileList
				) {
			if(str.contains(fileName)) {
				filePath = str;
				break;
			}
		}

		 try {
			 return MinioUtil.upload(new FileInputStream(new File(filePath)), fileName);

		 } catch (Exception e) {
			 e.printStackTrace();
		 }

		 return null;
	 }

	 /**
	 * 分页列表查询
	 *
	 * @param agJiucxldj
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "纠察巡逻登记-分页列表查询")
	@ApiOperation(value="纠察巡逻登记-分页列表查询", notes="纠察巡逻登记-分页列表查询")
	@GetMapping(value = "/list")
	@PermissionData(pageComponent = "problem/index")
	public Result<?> queryPageList(AgJiucxldj agJiucxldj,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<AgJiucxldj> queryWrapper = QueryGenerator.initQueryWrapper(agJiucxldj, req.getParameterMap());
		Page<AgJiucxldj> page = new Page<AgJiucxldj>(pageNo, pageSize);
		IPage<AgJiucxldj> pageList = agJiucxldjService.page(page, queryWrapper);
		return Result.ok(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param agJiucxldjPage
	 * @return
	 */
	@AutoLog(value = "纠察巡逻登记-添加")
	@ApiOperation(value="纠察巡逻登记-添加", notes="纠察巡逻登记-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody AgJiucxldjPage agJiucxldjPage) throws ParseException {
		AgJiucxldj agJiucxldj = new AgJiucxldj();
		BeanUtils.copyProperties(agJiucxldjPage, agJiucxldj);

		agJiucxldjService.saveMain(agJiucxldj, agJiucxldjPage.getAgJiucxldjResourceList());
		return Result.ok("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param agJiucxldjPage
	 * @return
	 */
	@AutoLog(value = "纠察巡逻登记-编辑")
	@ApiOperation(value="纠察巡逻登记-编辑", notes="纠察巡逻登记-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody AgJiucxldjPage agJiucxldjPage) {
		AgJiucxldj agJiucxldj = new AgJiucxldj();

		BeanUtils.copyProperties(agJiucxldjPage, agJiucxldj);
		AgJiucxldj agJiucxldjEntity = agJiucxldjService.getById(agJiucxldj.getId());
		if(agJiucxldjEntity==null) {
			return Result.error("未找到对应数据");
		}
		agJiucxldjService.updateMain(agJiucxldj, agJiucxldjPage.getAgJiucxldjResourceList());

		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		agJiucxldjService.applyAgain(agJiucxldj, user);

		return Result.ok("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "纠察巡逻登记-通过id删除")
	@ApiOperation(value="纠察巡逻登记-通过id删除", notes="纠察巡逻登记-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		agJiucxldjService.delMain(id);
		return Result.ok("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "纠察巡逻登记-批量删除")
	@ApiOperation(value="纠察巡逻登记-批量删除", notes="纠察巡逻登记-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.agJiucxldjService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "纠察巡逻登记-通过id查询")
	@ApiOperation(value="纠察巡逻登记-通过id查询", notes="纠察巡逻登记-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		AgJiucxldj agJiucxldj = agJiucxldjService.getById(id);
		if(agJiucxldj==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(agJiucxldj);

	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "纠察巡逻附件资源通过主表ID查询")
	@ApiOperation(value="纠察巡逻附件资源主表ID查询", notes="纠察巡逻附件资源-通主表ID查询")
	@GetMapping(value = "/queryAgJiucxldjResourceByMainId")
	public Result<?> queryAgJiucxldjResourceListByMainId(@RequestParam(name="id",required=true) String id) {
		List<AgJiucxldjResource> agJiucxldjResourceList = agJiucxldjResourceService.selectByMainId(id);
		return Result.ok(agJiucxldjResourceList);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param agJiucxldj
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, AgJiucxldj agJiucxldj) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<AgJiucxldj> queryWrapper = QueryGenerator.initQueryWrapper(agJiucxldj, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //Step.2 获取导出数据
      List<AgJiucxldj> queryList = agJiucxldjService.list(queryWrapper);
      // 过滤选中数据
      String selections = request.getParameter("selections");
      List<AgJiucxldj> agJiucxldjList = new ArrayList<AgJiucxldj>();
      if(oConvertUtils.isEmpty(selections)) {
          agJiucxldjList = queryList;
      }else {
          List<String> selectionList = Arrays.asList(selections.split(","));
          agJiucxldjList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
      }

      // Step.3 组装pageList
      List<AgJiucxldjPage> pageList = new ArrayList<AgJiucxldjPage>();
      for (AgJiucxldj main : agJiucxldjList) {
          AgJiucxldjPage vo = new AgJiucxldjPage();
          BeanUtils.copyProperties(main, vo);
          List<AgJiucxldjResource> agJiucxldjResourceList = agJiucxldjResourceService.selectByMainId(main.getId());
          vo.setAgJiucxldjResourceList(agJiucxldjResourceList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "纠察巡逻登记列表");
      mv.addObject(NormalExcelConstants.CLASS, AgJiucxldjPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("纠察巡逻登记数据", "导出人:"+sysUser.getRealname(), "纠察巡逻登记"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<AgJiucxldjPage> list = ExcelImportUtil.importExcel(file.getInputStream(), AgJiucxldjPage.class, params);
              for (AgJiucxldjPage page : list) {
                  AgJiucxldj po = new AgJiucxldj();
                  BeanUtils.copyProperties(page, po);
                  agJiucxldjService.saveMain(po, page.getAgJiucxldjResourceList());
              }
              return Result.ok("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.ok("文件导入失败！");
    }

    @PostMapping("/zhuanfa")
    public Result zhuanfa(@RequestBody AgJiucxldj dj){
		LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		this.agJiucxldjService.updateById(dj);
		this.agJiucxldjService.startFlow(dj,loginUser);
    	return Result.ok("成功");
	}


	 @GetMapping(value = "/myapplylist")
	 public Result<?> myApplyList(AgJiucxldj agLeave,
								  @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
								  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
								  HttpServletRequest req) {

		 Page<AgJiucxldj> page = new Page<AgJiucxldj>(pageNo, pageSize);
		 LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 IPage<AgJiucxldj> iPage = agJiucxldjService.myApplyList(page, user, agLeave);
		 if (iPage.getTotal() > 0) {
			 iPage.getRecords().forEach(record -> {
				 if (null != record.getEndTime()) {
					 record.setProcessStatus(ProcessKit.FLOW_STATUS_END);
				 } else {
					 if (null != record.getAuditStatus()) {
						 record.setProcessStatus(ProcessKit.FLOW_STATUS_RUNNING);
					 } else {
						 record.setProcessStatus(ProcessKit.FLOW_STATUS_NOT_SUBMIT);
					 }
				 }
			 });
		 }
		 return Result.ok(iPage);
	 }

	 @GetMapping(value = "/mytodolist")
	 public Result<?> myTodoList(AgJiucxldj agLeave,
								 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
								 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
								 HttpServletRequest req) {
		 Page<AgJiucxldj> page = new Page<AgJiucxldj>(pageNo, pageSize);
		 LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		 IPage<AgJiucxldj> iPage = agJiucxldjService.myTodoTasks(page, user, agLeave);
		 return Result.ok(iPage);
	 }

	 @GetMapping(value = "/mydonelist")
	 public Result<?> myDoneList(AgJiucxldj hqCggl,
								 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
								 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
								 HttpServletRequest req) {
		 Page<AgJiucxldj> page = new Page<AgJiucxldj>(pageNo, pageSize);
		 LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		 IPage<AgJiucxldj> iPage = agJiucxldjService.myDoneTasks(page, user, hqCggl);
		 if (iPage.getTotal() > 0) {
			 iPage.getRecords().forEach(record -> {
				 if (null != record.getEndTime()) {
					 record.setProcessStatus(ProcessKit.FLOW_STATUS_END);
				 } else {
					 record.setProcessStatus(ProcessKit.FLOW_STATUS_RUNNING);
				 }
			 });
		 }
		 return Result.ok(page);
	 }

	 @PostMapping(value = "/completetask")
	 public Result<?> completeTask(@RequestBody Map params) {
		 LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 agJiucxldjService.complateTask(loginUser, (String) params.get("taskId"), (Integer) params.get("auditStatus"),
				 (String) params.get("memo"));

		 return Result.ok("操作成功");
	 }
}
